package cn.antcore.resources.spring;

import cn.antcore.resources.Constants;
import cn.antcore.resources.config.Config;
import cn.antcore.resources.config.GlobalConfig;
import cn.antcore.resources.convert.impl.StringConvert;
import cn.antcore.resources.core.ResourcesRefresher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created By Hong on 2018/8/2
 **/
public class ResourcesEnvironment extends AbstractEnvironment {

    private static final Logger LOG = LoggerFactory.getLogger(ResourcesRefresher.class);

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
        super.postProcessEnvironment(configurableEnvironment, springApplication);

        Config config = GlobalConfig.readConfig(getSource());
        Map<String, Object> map = new HashMap<>();
        Set<Object> set = config.getConfig().keySet();
        Iterator<Object> iterable = set.iterator();
        while (iterable.hasNext()) {
            Object key = iterable.next();
            map.put(new StringConvert().convert(key), config.getConfig().get(key));
        }

        CompositePropertySource composite = new CompositePropertySource(Constants.SOURCE_NAME);
        composite.addPropertySource(new MapPropertySource(Constants.SOURCE_NAME, map));

        if (configurableEnvironment.getPropertySources().get(Constants.SOURCE_NAME) != null) {
            configurableEnvironment.getPropertySources().replace(Constants.SOURCE_NAME, composite);
        } else {
            configurableEnvironment.getPropertySources().addLast(composite);
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("Load Resources Successful.");
        }
    }
}
